package edu.hawaii.its381b.client;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.safehtml.shared.SafeUri;
import com.google.gwt.user.client.ui.Image;

public class BackgroundMusic {

	private int CanvasDrawLocationX;
	private int CanvasDrawLocationY;
	private ImageElement buttonOnImage;
	private ImageElement buttonOffImage;
	private ImageElement currentButtonImage;

	//Size in pixels of image sides
	private int buttonSize = 50;
	private BackgroundAudioPanel music;
	private Canvas canvas;
	boolean musicIsOn;
	boolean canPlay = true;
	boolean firstPlay = true;

	public BackgroundMusic(int canvasWidthAmount, int canvasHeightAmount,
			int borderAmount, Canvas canvas)
	{
		music = new BackgroundAudioPanel(HermitCrabResources.INSTANCE.backgroundMusic().getSafeUri().asString());
		
		canPlay = true;
		
		this.canvas = canvas;
		this.CanvasDrawLocationX = canvasWidthAmount - buttonSize;
		this.CanvasDrawLocationY = borderAmount/2;

		SafeUri buttonOnImageURI = HermitCrabResources.INSTANCE.buttonMusicOn().getSafeUri();
		this.buttonOnImage = ImageElement.as((new Image(buttonOnImageURI)).getElement());

		SafeUri buttonOffImageURI = HermitCrabResources.INSTANCE.buttonMusicOff().getSafeUri();
		this.buttonOffImage = ImageElement.as((new Image(buttonOffImageURI)).getElement());

		if(canPlay) {
			turnOn();	
		} else {
			currentButtonImage = this.buttonOffImage;
			drawButton();
		}
	}

	public int getButtonSize(){
		return buttonSize;
	}

	public boolean myMusicIsOn(){
		return musicIsOn;
	}

	public void hitButton(){
		if(musicIsOn){
			turnOff();
		}else{
			turnOn();
		}
	}

	public void toggleMusicButtonIfPressed(int touchedX, int touchedY){
		if (touchedX >= CanvasDrawLocationX && touchedX <= CanvasDrawLocationX + buttonSize && 
				touchedY >= CanvasDrawLocationY && touchedY <= CanvasDrawLocationY + buttonSize){
			hitButton();
		}
	}

	public void turnOn(){
		//the Can Play check safeguards against calling audio commands when no audio is available
		if(canPlay){
			currentButtonImage = this.buttonOnImage;
			drawButton();
			musicIsOn = true;
			music.play();					
		}
	}

	public void turnOff(){
		currentButtonImage = this.buttonOffImage;
		drawButton();
		musicIsOn = false;

		//the Can Play check safeguards against calling audio commands when no audio is available
		if(canPlay){
			music.pause();
		}
	}
	
	public void loadAudio() {
		music.load();
	}

	public void drawButton(){
		canvas.getContext2d().drawImage(currentButtonImage,
				CanvasDrawLocationX, CanvasDrawLocationY,
				buttonSize, buttonSize);
	}
}
